﻿#region Using

using System;
using System.Net;
using WSMon.Core.Configuration;
using WSMon.Core.Interfaces;

#endregion

namespace WSMon.Core.Checkers.Web
{
    public class FtpChecker : Checker, IChecker
    {
        private readonly FtpConfiguration _ftpConfiguration;

        private string _logs = string.Empty;

        public FtpChecker(FtpConfiguration ftpConfiguration)
        {
            if (ftpConfiguration == null)
                throw new ArgumentNullException("ftpConfiguration");

            _ftpConfiguration = ftpConfiguration;
        }

        #region IChecker Members

        public bool CheckOut()
        {
            try
            {
                var request =
                    (FtpWebRequest)
                    WebRequest.Create(string.Format("{0}:{1}/{2}", _ftpConfiguration.Host, _ftpConfiguration.Port,
                                                    _ftpConfiguration.RemoteFolder));

                request.EnableSsl = _ftpConfiguration.EnableSsl;

                if (_ftpConfiguration.NetworkCredential != null)
                    request.Credentials = _ftpConfiguration.NetworkCredential;

                request.Method = WebRequestMethods.Ftp.ListDirectory;

                var response = (FtpWebResponse) request.GetResponse();
                bool retVal = response.StatusCode == FtpStatusCode.DataAlreadyOpen;
                response.Close();

                return retVal;
            }
            catch (Exception ex)
            {
                _logs = ex.Message;
                return false;
            }
        }

        public string GetLogs()
        {
            return _logs;
        }

        #endregion
    }
}